package com.nwpu.intimacy.login;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.utils.CacheUtil;

public class RegisterActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/register";

	private EditText regist_username_edit;
	private EditText regist_phonenumber_edit;
	private EditText regist_email_edit;
	private EditText regist_password_edit;
	private EditText regist_password_edit_repeat;
	private EditText regist_yanzheng_edit;

	private Button refresh_code;
	private ImageView checkCodeImageView;

	private Button regist_button;
	private Button cancel_button;

	private ImageView regist_image;

	private String getCode = null;

	private Handler loginHandler;

	private Boolean isPhoto = false;

	private final static int USER_LOGIN_SUCCESS = 0x114;
	private final static int USER_LOGIN_FAIL = 0x115;
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESIZE_REQUEST_CODE = 2;

	private static final String IMAGE_FILE_NAME = "header.jpg";

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_registered);

		initActionBar();

		initLayout();

		regist_email_edit
				.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

		checkCodeImageView.setImageBitmap(Code.getInstance().getBitmap());
		getCode = Code.getInstance().getCode(); // 获取显示的验证码

		// 线程交互
		loginHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_LOGIN_SUCCESS: {
					// 跳转界面 登录成功

					Toast.makeText(getApplicationContext(), "Login Success!",
							Toast.LENGTH_SHORT).show();

					finish();

					break;
				}
				case USER_LOGIN_FAIL: {

					// 注册失败，提示用户信息
					Toast.makeText(getApplicationContext(),
							"Username repeat, please re-register!",
							Toast.LENGTH_SHORT).show();
					break;

				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.regist_image:// 点击头像显示头像

			onImageChoiceDialog();

			break;
		case R.id.refresh:// 点击二维码图片
			checkCodeImageView.setImageBitmap(Code.getInstance().getBitmap());
			getCode = Code.getInstance().getCode();
			break;
		case R.id.regist_button:// 点击注册按钮

			// 验证注册信息完整性
			if (!checkInformation()) {

				return;

			}

			registerUser();// 向服务器发送注册请求
			break;
		case R.id.cancel_button:// 点击关闭按钮
			finish();
			break;
		}

	}

	// 初始化控件
	private void initLayout() {

		regist_username_edit = (EditText) findViewById(R.id.regist_username_edit);
		regist_phonenumber_edit = (EditText) findViewById(R.id.regist_phonenumber_edit);
		regist_email_edit = (EditText) findViewById(R.id.regist_email_edit);
		regist_password_edit = (EditText) findViewById(R.id.regist_password_edit);
		regist_password_edit_repeat = (EditText) findViewById(R.id.regist_password_edit_repeat);
		regist_yanzheng_edit = (EditText) findViewById(R.id.regist_yanzheng_edit);

		refresh_code = (Button) findViewById(R.id.refresh);
		checkCodeImageView = (ImageView) findViewById(R.id.yanzheng_image);

		regist_button = (Button) findViewById(R.id.regist_button);
		cancel_button = (Button) findViewById(R.id.cancel_button);

		regist_image = (ImageView) findViewById(R.id.regist_image);

	}

	// 设置用户头像
	private void onImageChoiceDialog() {

		new AlertDialog.Builder(this)
				.setTitle("Set Profile Photo")
				.setItems(
						new String[] { "Choose from a mobile photo album",
								"Photograph" },
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								switch (which) {
								case 0:

									Intent galleryIntent = new Intent(
											Intent.ACTION_GET_CONTENT);
									galleryIntent
											.addCategory(Intent.CATEGORY_OPENABLE);
									galleryIntent.setType("image/*");
									startActivityForResult(galleryIntent,
											IMAGE_REQUEST_CODE);

									break;
								case 1:

									if (isSdcardExisting()) {
										Intent cameraIntent = new Intent(
												"android.media.action.IMAGE_CAPTURE");
										cameraIntent.putExtra(
												MediaStore.EXTRA_OUTPUT,
												getImageUri());
										cameraIntent.putExtra(
												MediaStore.EXTRA_VIDEO_QUALITY,
												0);
										startActivityForResult(cameraIntent,
												CAMERA_REQUEST_CODE);
									} else {
										Toast.makeText(getApplicationContext(),
												"Please insert the sd card!",
												Toast.LENGTH_LONG).show();
									}

									break;

								}

							}
						}

				).show();

	}

	public void initActionBar() {

		getActionBar().setTitle("Intimacy");
		getActionBar().setDisplayShowHomeEnabled(false);
		getActionBar().show();

	}

	// 验证用户信息的完整性
	private boolean checkInformation() {

		String regist_usernameString = regist_username_edit.getText()
				.toString();
		String regist_phonenumberString = regist_phonenumber_edit.getText()
				.toString();
		String regist_emailString = regist_email_edit.getText().toString();
		String regist_password_1_String = regist_password_edit.getText()
				.toString();
		String regist_password_2_String = regist_password_edit_repeat.getText()
				.toString();
		String regist_yanzhengString = regist_yanzheng_edit.getText()
				.toString();

		if (regist_usernameString.equals("")
				|| regist_phonenumberString.equals("")
				|| regist_emailString.equals("")
				|| regist_password_1_String.equals("")
				|| regist_password_2_String.equals("")
				|| regist_yanzhengString.equals("")) {

			Toast.makeText(getApplicationContext(),
					"Please fill in all the information to complete!",
					Toast.LENGTH_SHORT).show();

			return false;

		}

		if (!isMobileNO(regist_phonenumberString)) {

			return false;

		}

		if (!isEmail(regist_emailString)) {

			return false;

		}

		if (regist_password_1_String.equals(regist_password_2_String)) {

			if (regist_password_1_String.length() < 6) {

				Toast.makeText(getApplicationContext(),
						"Password length is too short, please re-enter!",
						Toast.LENGTH_SHORT).show();
				return false;

			}

			if (regist_password_1_String.length() > 16) {

				Toast.makeText(getApplicationContext(),
						"Password length is too long, please re-enter!",
						Toast.LENGTH_SHORT).show();
				return false;

			}

		} else {

			Toast.makeText(getApplicationContext(),
					"The passwords do not match, please re-enter!",
					Toast.LENGTH_SHORT).show();
			return false;

		}

		if (!regist_yanzhengString.equals(getCode)) {

			Toast.makeText(getApplicationContext(),
					"Verification code input errors, please re-enter!",
					Toast.LENGTH_SHORT).show();
			return false;

		}

		if (!isPhoto) {

			Toast.makeText(getApplicationContext(),
					"Please Set Profile Photo!",
					Toast.LENGTH_SHORT).show();
			return false;

		}

		return true;
	}

	// 向服务器发送用户的注册申请
	private void registerUser() {

		new Thread() {

			public void run() {

				try {

					String regist_usernameString = regist_username_edit
							.getText().toString();
					String regist_phonenumberString = regist_phonenumber_edit
							.getText().toString();
					String regist_emailString = regist_email_edit.getText()
							.toString();
					String regist_password_1_String = regist_password_edit
							.getText().toString();

					String photo_str = bitmaptoString(CacheUtil.GetFromFile(
							"UserPhoto", "Photo"));

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username", regist_usernameString);
					jsonObject.put("password", regist_password_1_String);
					jsonObject.put("phonenumber", regist_phonenumberString);
					jsonObject.put("email", regist_emailString);
					jsonObject.put("image", photo_str);

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("regist",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							HTTP.UTF_8));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(httpResponse
							.getEntity());

					Log.e("regist", result.toString());

					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("status").equals("success")) {

						Message msg = new Message();
						msg.what = USER_LOGIN_SUCCESS;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_LOGIN_FAIL;
						msg.obj = result;
						loginHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}.start();

	}

	// 验证邮箱的正确性
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	// 验证手机号的正确性
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		} else {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				resizeImage(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				if (isSdcardExisting()) {
					resizeImage(getImageUri());
				} else {
					Toast.makeText(RegisterActivity.this,
							"Memory card not found, you can not store photos!",
							Toast.LENGTH_LONG).show();
				}
				break;

			case RESIZE_REQUEST_CODE:
				if (data != null) {
					showResizeImage(data);
				}
				break;
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean isSdcardExisting() {
		final String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public void resizeImage(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESIZE_REQUEST_CODE);
	}

	private void showResizeImage(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			try {
				Bitmap photo = extras.getParcelable("data");
				Drawable drawable = new BitmapDrawable(photo);
				regist_image.setImageDrawable(drawable);

				CacheUtil.WriteToFile("UserPhoto", photo, "Photo");

				isPhoto = true;

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private Uri getImageUri() {
		return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
				IMAGE_FILE_NAME));
	}

	public String bitmaptoString(Bitmap bitmap) {

		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

}
